package com.sync.data.common.obj;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.sync.data.common.obj.annoation.ObjectPrefix;
import com.sync.data.common.util.EntityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * @author liquanchang
 */
@Component
@Slf4j
public class ObjectInit {

    @PersistenceContext
    EntityManager em;

    @PostConstruct
    public void init() {

        log.info("================================初始化对象前缀start================================");

        List<Class<?>> allEntityClass = EntityUtils.getAllEntityClass(em);
        List<String> excludeList = CollUtil.newArrayList("SysUserRelation", "ViewCrmVisitPlanWeek", "ViewCrmVisitPlanMonth");
        for(Class<?> entityClass : allEntityClass){
            String className = ClassUtil.getClassName(entityClass,true);

            if(!excludeList.contains(className)){
                ObjectPrefix objectPrefix = entityClass.getAnnotation(ObjectPrefix.class);

                if(ObjectUtil.isNull(objectPrefix)){
                    log.warn("============================对象:"+ className+",需定义四位对象编号");
                }

//                Assert.notNull(objectPrefix,"对象:"+ className+",需定义四位对象编号");
                String value = objectPrefix.value();

                if(StrUtil.isEmpty(value)){
                    log.warn("============================对象:"+ className+",需定义四位对象编号");
                }

//                Assert.notNull(value,"对象:"+ className+",需定义四位对象编号");

                Object object = ObjectNo.objectNo.get(value);

                if(ObjectUtil.isNotNull(object)){
                    log.warn("============================对象:"+ className+"与对象:"+object+",四位对象编号重复"+"编号为:"+value);
                }

//                Assert.isNull(object,"对象:"+ className+"与对象:"+object+",四位对象编号重复"+"编号为:"+value);

                ObjectNo.objectNo.put(value, className);

                log.info("Object:{},Code:{}",className,value);
            }
        }

        log.info("================================初始化对象前缀end================================");
    }

}
